from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, JSON, Text, Boolean
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from datetime import datetime
from database import Base


class DetectionLog(Base):
    """
    检测日志模型
    记录每次检测的结果、触发拍照的时间与照片存储路径
    """
    __tablename__ = "detection_logs"

    id = Column(Integer, primary_key=True, index=True)
    
    # 关联信息
    drone_id = Column(Integer, ForeignKey('drones.id'), nullable=False, index=True)
    task_id = Column(Integer, ForeignKey('tasks.id'), nullable=True, index=True)
    flight_log_id = Column(Integer, ForeignKey('flight_logs.id'), nullable=True, index=True)  # 关联到具体的飞行日志
    detection_target_id = Column(Integer, ForeignKey('detection_targets.id'), nullable=True, index=True)  # 检测目标
    detection_model_id = Column(Integer, ForeignKey('detection_models.id'), nullable=True, index=True)  # 使用的检测模型
    model_version_id = Column(Integer, ForeignKey('model_versions.id'), nullable=True, index=True)  # 使用的模型版本
    
    # 检测时间信息
    detection_time = Column(DateTime(timezone=True), server_default=func.now(), index=True)  # 检测时间
    photo_time = Column(DateTime(timezone=True), nullable=True, index=True)  # 触发拍照时间
    
    # 检测结果位置信息
    latitude = Column(Float, nullable=False)  # 检测到的目标纬度
    longitude = Column(Float, nullable=False)  # 检测到的目标经度
    altitude = Column(Float, nullable=False)  # 检测到的目标高度（米）
    
    # 检测结果信息
    confidence = Column(Float, nullable=False)  # 置信度（0-100）
    detection_result = Column(JSON, nullable=True)  # 详细检测结果（JSON格式）
    is_positive = Column(Boolean, default=True, comment="是否为正样本")
    
    # 照片信息
    photo_path = Column(String(500), nullable=True)  # 照片存储路径
    photo_thumbnail_path = Column(String(500), nullable=True)  # 缩略图路径
    photo_metadata = Column(JSON, nullable=True)  # 照片元数据（分辨率、大小等）
    
    # 附加信息
    notes = Column(Text, nullable=True)  # 备注信息
    processed = Column(Boolean, default=False, comment="是否已处理")
    
    # 系统字段
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联关系
    drone = relationship("Drone", backref="detection_logs")
    task = relationship("Task", backref="detection_logs")
    flight_log = relationship("FlightLog", backref="detection_logs")
    detection_target = relationship("DetectionTarget", backref="detection_logs")
    detection_model = relationship("DetectionModel", backref="detection_logs")
    model_version = relationship("ModelVersion", backref="detection_logs")